<template>
  <div class="body1">
    <div class="no-print el-button-print">
      <el-button @click="exportPDF">导出为pdf</el-button>
    </div>

    <div class="body2" id="pdfDom" :class="{ 'pdf-export': isPdfExport }">
      <div class="title">
        <div class="biaotididian">{{ agencyName }}</div>
        <div class="biaoti">行政处罚决定书</div>
      </div>
      <div class="foreword1">
        <input v-model="form.a1" :resize="'none'" autosize maxlength="4" class="inputStyle1"
          style="width: 80px;font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea">
        <span>（</span>
        <reference-select style="width: 5mm;margin-bottom: 4px" v-model="form.referenceValue"
          class="InvestigatorSelectReplace" />
        <span>）罚决字[</span>
        <input v-model="form.a2" :resize="'none'" autosize maxlength="4" class="areaInputStyle"
          style="width: 40px;font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea"
          oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')">
        <span>]第</span>
        <input v-model="form.a3" :resize="'none'" autosize maxlength="5" class="areaInputStyle"
          style="width: 50px;font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea"
          oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')">
        <span>号</span>
      </div>
      <div class="el-button-addAndDel">
        <el-button @click="addClient">添加当事人</el-button>
        <el-button @click="delClient">删除当事人</el-button>
      </div>
      <div v-for="(item, index) in form.client" :key="index" class="calculate-pagination-style"
        :class="{ 'page-break': controlPage.includes('client' + `${index}`) }"
        style="height: calc(4 * 35px); line-height: 35px;">
        <div v-if="index === 0" style="display: inline-block; position: relative;">
          <span>&nbsp;&nbsp;&nbsp;&nbsp;当事人：</span>
          <privy-info-select v-model="form.client[index]" v-model:isSelected="form.isUnit"
            return-fields="A  法人代表：C，职务：D，住址：E，企业类型：F，经营范围：G，社会信用代码（营业执照注册号）：B，联系电话：H" :rowConfig="clientConfig">
          </privy-info-select>
        </div>
        <div v-else style="display: inline-block; position: relative;">
          <span>&nbsp;&nbsp;&nbsp;&nbsp;当事人：</span>
          <privy-info-select v-model="form.client[index]"
            return-fields="A  法人代表：C，职务：D，住址：E，企业类型：F，经营范围：G，社会信用代码（营业执照注册号）：B，联系电话：H" :rowConfig="clientConfig">
          </privy-info-select>
        </div>
      </div>
      <div class="calculate-pagination-style" style="line-height: 35px;"
        :class="{ 'page-break': controlPage.includes('p1') }">
        <span>&nbsp;&nbsp;&nbsp;&nbsp;你</span>
        <span :class="{ 'del-line-style': !form.isUnit }" @click="switchUnitDelLine">（单位）</span>
        <span>于</span>
        <editable-textarea :text="form.date1" param-type="YYYYMMDD1" @send-to-parent="receiveFromChild" />
        <span>实施了</span>
        <LawsAndRegulationsSelect v-model:illegalActText="form.a4" v-model:returnIllegalTermsString="form.a5"
          v-model:returnIllegalBasisString="form.a6" width="100px" />
        <span>的行为，涉嫌违反了</span>
        <span v-if="form.a5" class="span-underline">{{ form.a5 }}</span><span v-else
          class="span-underline">&nbsp;&nbsp;</span>
        <span>的规定，本机关于</span>
        <editable-textarea :text="form.date2" param-type="YYYYMMDD2" @send-to-parent="receiveFromChild" />
        <span>立案调查。</span>
      </div>
      <div class="calculate-pagination-style " style="height: calc(3 * 35px); line-height: 35px;"
        :class="{ 'page-break': controlPage.includes('p2') }">
        <span>&nbsp;&nbsp;&nbsp;&nbsp;经查明，</span>
        <CrossRowInput v-model:value="form.a7" :line-config="a7Config"></CrossRowInput>
      </div>
      <div class="calculate-pagination-style" style="height: calc(1 * 35px); "
        :class="{ 'page-break': controlPage.includes('p3') }">
        <span>&nbsp;&nbsp;&nbsp;&nbsp;上诉事实，由以下证据证实：</span>
      </div>
      <div class="el-button-addAndDel">
        <el-button @click="addProve">添加证据</el-button>
        <el-button @click="delProve">删除证据</el-button>
      </div>
      <div v-for="(item, index) in form.evidence" :key="index" class="calculate-pagination-style"
        :class="{ 'page-break': controlPage.includes('evidence' + `${index}`) }"
        style="height: calc(2 * 35px); line-height: 35px;">
        <span>&nbsp;&nbsp;&nbsp;&nbsp;证据：</span>
        <input v-model="item.name" :resize="'none'" autosize maxlength="15" class="inputStyle1"
          style="width: calc(15 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
        <span>，证明：</span>
        <CrossRowInput v-model:value="item.prove" :line-config="proveConfig"></CrossRowInput>
      </div>
      <div class="calculate-pagination-style" style="height: calc(1 * 35px);"
        :class="{ 'page-break': controlPage.includes('p4') }">
        <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
        <editable-textarea :text="form.date3" param-type="YYYYMMDD3" @send-to-parent="receiveFromChild" />
        <span>，本机关依法向你</span>
        <span :class="{ 'del-line-style': !form.isUnit }" @click="switchUnitDelLine">（单位）</span>
        <span>送达了《行政处罚事先（</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(1 * 35px);"
        :class="{ 'page-break': controlPage.includes('p5') }">
        <span>听证）告知书（</span>
        <input v-model="form.a8" :resize="'none'" autosize maxlength="4" class="inputStyle1"
          style="width: 80px;font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea">
        <span>（</span>
        <reference-select style="width: 5mm;margin-bottom: 4px" v-model="form.referenceValue"
          class="InvestigatorSelectReplace" />
        <span>）罚先告字[</span>
        <input v-model="form.a9" :resize="'none'" autosize maxlength="4" class="areaInputStyle"
          style="width: 40px;font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea"
          oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')">
        <span>]第</span>
        <input v-model="form.a10" :resize="'none'" autosize maxlength="5" class="areaInputStyle"
          style="width: 50px;font-family: 仿宋;font-size: 5mm;text-align: center" type="textarea"
          oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')">
        <span>号），告知你（单</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(1 * 35px);"
        :class="{ 'page-break': controlPage.includes('p6') }">
        <span>位）拟作出行政处罚决定的事实、理由、依据及内容，并告知你</span>
        <span :class="{ 'del-line-style': !form.isUnit }" @click="switchUnitDelLine">（单位）</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(1 * 35px);"
        :class="{ 'page-break': controlPage.includes('p7') }">
        <span>依法享有的权利。你</span>
        <span :class="{ 'del-line-style': !form.isUnit }" @click="switchUnitDelLine">（单位）</span>
        <span>在规定期限内未提出陈诉、申辩[以及听证]</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(1 * 35px);"
        :class="{ 'page-break': controlPage.includes('p8') }">
        <span>要求。</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(1 * 35px);"
        :class="{ 'page-break': controlPage.includes('p9') }">
        <span>
          &nbsp;&nbsp;&nbsp;&nbsp;<span :class="{ 'del-line-style': form.isPlead }"
            @click="switchPleadDelLine">[&nbsp;你</span>
          <span :class="{ 'del-line-style': !form.isUnit || form.isPlead }" @click="switchUnitDelLine">（单位）</span>
        </span>
        <span v-if="!form.isPlead">
          <editable-textarea :text="form.date4" param-type="YYYYMMDD4" @send-to-parent="receiveFromChild" />
        </span>
        <span v-if="form.isPlead" @click="switchPleadDelLine" class="del-line-style">&emsp;&emsp;年&emsp;月&emsp;日</span>
        <span :class="{ 'del-line-style': form.isPlead }" @click="switchPleadDelLine">向本机关提出陈述、申辩（听证要求）</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(2 * 35px); line-height: 35px;"
        :class="{ 'page-break': controlPage.includes('p10') }">
        <span :class="{ 'del-line-style': form.isPlead }" @click="switchPleadDelLine">。你</span>
        <span :class="{ 'del-line-style': !form.isUnit || form.isPlead }" @click="switchUnitDelLine">（单位）</span>
        <span :class="{ 'del-line-style': form.isPlead }" @click="switchPleadDelLine">辩称</span>
        <CrossRowInput v-if="!form.isPlead" v-model:value="form.a11" :line-config="a11Config"></CrossRowInput>
        <span v-if="form.isPlead" class="del-line-style" @click="switchPleadDelLine"
          style=" width: 120mm; border-bottom: 1px solid black;">&emsp;</span>
        <span v-if="form.isPlead" class="del-line-style" @click="switchPleadDelLine"
          style=" width: 160mm; border-bottom: 1px solid black;">&emsp;</span>
      </div>
      <div class="calculate-pagination-style " style="height: calc(4 * 35px); line-height: 35px;"
        :class="{ 'page-break': controlPage.includes('p11') }">
        &nbsp;&nbsp;&nbsp;&nbsp;<span :class="{ 'del-line-style': form.isPlead }"
          @click="switchPleadDelLine">本机关认为</span>
        <CrossRowInput v-if="!form.isPlead" v-model:value="form.a12" :line-config="a12Config"></CrossRowInput>
        <span v-if="form.isPlead" class="del-line-style" @click="switchPleadDelLine"
          style=" width: 125mm; border-bottom: 1px solid black;">&emsp;</span>
        <span v-if="form.isPlead" class="del-line-style" @click="switchPleadDelLine"
          style=" width: 160mm; border-bottom: 1px solid black;">&emsp;</span>
        <span v-if="form.isPlead" class="del-line-style" @click="switchPleadDelLine"
          style=" width: 160mm; border-bottom: 1px solid black;">&emsp;</span>
        <span v-if="form.isPlead" class="del-line-style" @click="switchPleadDelLine"
          style=" width: 155mm; border-bottom: 1px solid black;">&emsp;</span>
        <span :class="{ 'del-line-style': form.isPlead }" @click="switchPleadDelLine">&nbsp;]</span>

      </div>
      <div class="calculate-pagination-style" style="line-height: 35px;"
        :class="{ 'page-break': controlPage.includes('p12') }">
        <span>&nbsp;&nbsp;&nbsp;&nbsp;本机关认为，你</span>
        <span :class="{ 'del-line-style': !form.isUnit }" @click="switchUnitDelLine">（单位）</span>
        <LawsAndRegulationsSelect v-model:illegalActText="form.a13" v-model:returnIllegalTermsString="form.a14"
          v-model:returnIllegalBasisString="form.a15" width="100px" />
        <span>的行为，违反了</span>
        <span v-if="form.a14" class="span-underline">{{ form.a14 }}</span><span v-else
          class="span-underline">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
        <span>的规定，根据</span>
        <span v-if="form.a15" class="span-underline">{{ form.a15 }}</span><span v-else
          class="span-underline">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
        <span>的规定，应当</span>
        <CrossRowInput v-model:value="form.a16" :line-config="a16Config"></CrossRowInput>
        <span>。</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(2 * 35px); line-height: 35px;"
        :class="{ 'page-break': controlPage.includes('p13') }">
        <span>&nbsp;&nbsp;&nbsp;&nbsp;鉴于当事人</span>
        <CrossRowInput v-model:value="form.a17" :line-config="a17Config"></CrossRowInput>
        <span>，根</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(1 * 35px);"
        :class="{ 'page-break': controlPage.includes('p14') }">
        <span>据</span>
        <input v-model="form.a18" :resize="'none'" autosize maxlength="25" class="inputStyle1"
          style="width: calc(25 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
        <span>的规定，对你</span>
      </div>
      <div class="calculate-pagination-style " style="height: calc(2 * 35px); line-height: 35px;"
        :class="{ 'page-break': controlPage.includes('p15') }">
        <span :class="{ 'del-line-style': !form.isUnit }" @click="switchUnitDelLine">（单位）</span>
        <span>作出如下行政处罚：</span>
        <CrossRowInput v-model:value="form.a19" :line-config="a19Config"></CrossRowInput>
        <span>。</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(1 * 35px);"
        :class="{ 'page-break': controlPage.includes('p16') }">
        <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
        <span :class="{ 'del-line-style': form.isHaveForfeit }" @click="switchForfeitDelLine">上诉罚款，你</span>
        <span :class="{ 'del-line-style': !form.isUnit || form.isHaveForfeit }" @click="switchUnitDelLine">（单位）</span>
        <span :class="{ 'del-line-style': form.isHaveForfeit }"
          @click="switchForfeitDelLine">应当自收到本处罚决定书之日起15日内，持本</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(2 * 35px);"
        :class="{ 'page-break': controlPage.includes('p17') }">
        <span :class="{ 'del-line-style': form.isHaveForfeit }" @click="switchForfeitDelLine">决定书，到指定</span>
        <CrossRowInput v-if="!form.isHaveForfeit" v-model:value="form.a20" :line-config="a20Config"></CrossRowInput>
        <span v-if="form.isHaveForfeit" class="del-line-style" @click="switchForfeitDelLine"
          style=" width: 125mm; border-bottom: 1px solid black;">&emsp;</span>
        <span v-if="form.isHaveForfeit" class="del-line-style" @click="switchForfeitDelLine"
          style=" width: 75mm; border-bottom: 1px solid black;">&emsp;</span>
        <span :class="{ 'del-line-style': form.isHaveForfeit }" @click="switchForfeitDelLine">缴纳。逾期不缴纳罚款的，本机关将根</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(1 * 35px);"
        :class="{ 'page-break': controlPage.includes('p18') }">
        <span :class="{ 'del-line-style': form.isHaveForfeit }"
          @click="switchForfeitDelLine">据《中华人民共和国行政处罚法》第七十二条的规定，每日按罚款数额的</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(1 * 35px);"
        :class="{ 'page-break': controlPage.includes('p19') }">
        <span :class="{ 'del-line-style': form.isHaveForfeit }" @click="switchForfeitDelLine">百分之三加处罚款。</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(2 * 35px); line-height: 35px;"
        :class="{ 'page-break': controlPage.includes('p20') }">
        <span>&nbsp;&nbsp;&nbsp;&nbsp;如不服本处罚决定，可以在收到本决定书之日起60日内向</span>
        <CrossRowInput v-model:value="form.a21" :line-config="a21Config"></CrossRowInput>
        <span>申请行政复议；也可以在收</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(1 * 35px);"
        :class="{ 'page-break': controlPage.includes('p21') }">
        <span>到本决定书之日起 6个月内直接向</span>
        <input v-model="form.a22" :resize="'none'" autosize maxlength="10" class="inputStyle1"
          style="width: calc(10 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
        <span>人民法院起诉，</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(1 * 35px);"
        :class="{ 'page-break': controlPage.includes('p22') }">
        <span>但本决定不停止执行，法律另有规定的除外。逾期不申请行政复议、不提</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(1 * 35px);"
        :class="{ 'page-break': controlPage.includes('p23') }">
        <span>起行政诉讼又不履行的，本机关将依法申请人民法院强制执行或依照有关</span>
      </div>
      <div class="calculate-pagination-style" style="height: calc(1 * 35px);"
        :class="{ 'page-break': controlPage.includes('p24') }">
        <span>规定强制执行。</span>
      </div>
      <div :style="{ 'height': `calc(${sealPosition} * 35px)` }">
        <!-- 这个div用来控制最后一页盖章绝对保证在这一页的最下方 -->
      </div>
      <div class="calculate-pagination-style">
        <div style="text-align: right; margin-top: 60px; margin-bottom: 20px;">
          <div class="seal-container">
            <span class="seal-name" v-html="sealName"></span>
            <div class="delivery-agency-div" :class="{ 'official-seal-display': isDisplay }">
              <editable-textarea :text="form.date5" param-type="YYYYMMDD5" @send-to-parent="receiveFromChild" />
              <img class="official-seal" src="../../assets/tupian.png" alt="Image">
            </div>
          </div>
        </div>
        <div style="line-height: 30px;">
          <span>联&nbsp;系&nbsp;人：</span><input v-model="form.a23" :resize="'none'" autosize maxlength="6"
            class="inputStyle1" style="width: calc(6 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
          <span>联系地址：</span><input v-model="form.a24" :resize="'none'" autosize maxlength="16" class="inputStyle1"
            style="width: calc(16 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
          <br><span>联系电话：</span><input v-model="form.a25" :resize="'none'" autosize maxlength="12" class="inputStyle1"
            style="width: calc(6 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea"
            oninput="this.value = this.value.replace(/[^a-zA-Z0-9_-]/g, '')">
          <span>邮政编码：</span><input v-model="form.a26" :resize="'none'" autosize maxlength="16" class="inputStyle1"
            style="width: calc(16 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
        </div>
      </div>

    </div>
  </div>


</template>

<script>
import EditableTextarea from "@/views/template/EditableTextarea";
import { agencyName, sealName } from "../../utils/publicName.js";
import PrivyInfoSelect from "@/views/template/PrivyInfoSelect";
import LawsAndRegulationsSelect from "@/views/template/LawsAndRegulationsSelect";
import CrossRowInput from "@/views/template/CrossRowInput";
import ReferenceSelect from "@/views/template/ReferenceSelect";
import { confirmRows, countChars } from "@/utils/ConfirmRows";

export default {
  components: {
    LawsAndRegulationsSelect,
    EditableTextarea,
    CrossRowInput,
    ReferenceSelect,
    PrivyInfoSelect,
  },

  data() {
    return {
      agencyName: agencyName,
      sealName: sealName,
      form: {
        client: [''],
        evidence: [{
          name: '',
          prove: ''
        }],
        // 控制删除线
        isHaveForfeit: false, // 是否有罚款处罚
        isUnit: true, //是否是单位
        isPlead: false, // 是否有申辩陈诉
      },
      page: {
        client: 4, p1: 2, p2: 3, p3: 1, evidence: 2,
        p4: 1, p5: 1, p6: 1, p7: 1, p8: 1, p9: 1, p10: 2,
        p11: 4, p12: 3, p13: 2, p14: 1, p15: 2, p16: 1,
        p17: 2, p18: 1, p19: 1, p20: 2, p21: 1, p22: 1, p23: 1, p24: 1
      }, // 对应小模块内容有几行（p1和p12会动态调整）。
      controlPage: [], // 控制分页符
      sealPosition: 0, // 控制盖章的位置

      status: '', //当前文书的状态
      isPdfExport: false, //控制打印样式
      isDisplay: true, //控制官方印章的显示
      clientConfig: {
        firstLine: { chars: 26 * 2 },
        middleLines: { count: 2, chars: 32 * 2 },
        lastLine: { chars: 32 * 2 }
      },
      a7Config: {
        firstLine: { chars: 26 * 2 },
        middleLines: { count: 1, chars: 32 * 2 },
        lastLine: { chars: 32 * 2 }
      },
      proveConfig: {
        firstLine: { chars: 8 * 2 },
        middleLines: { count: 0, chars: 32 * 2 },
        lastLine: { chars: 32 * 2 }
      },
      a11Config: {
        firstLine: { chars: 24 * 2 },
        middleLines: { count: 0, chars: 32 * 2 },
        lastLine: { chars: 32 * 2 }
      },
      a12Config: {
        firstLine: { chars: 25 * 2 },
        middleLines: { count: 2, chars: 32 * 2 },
        lastLine: { chars: 31 * 2 }
      },
      a16Config: {
        firstLine: { chars: 18 * 2 },
        middleLines: { count: 0, chars: 32 * 2 },
        lastLine: { chars: 31 * 2 }
      },
      a17Config: {
        firstLine: { chars: 25 * 2 },
        middleLines: { count: 0, chars: 32 * 2 },
        lastLine: { chars: 30 * 2 }
      },
      a19Config: {
        firstLine: { chars: 19 * 2 },
        middleLines: { count: 0, chars: 32 * 2 },
        lastLine: { chars: 31 * 2 }
      },
      a20Config: {
        firstLine: { chars: 25 * 2 },
        middleLines: { count: 0, chars: 32 * 2 },
        lastLine: { chars: 15 * 2 }
      },
      a21Config: {
        firstLine: { chars: 5 * 2 },
        middleLines: { count: 0, chars: 32 * 2 },
        lastLine: { chars: 20 * 2 }
      },
    }
  },
  watch: {
    // 监听违法依据变化,来处理地址的动态调整
    'form.a13': {
      handler(newVal, oldVal) {
        this.adjustA16Width();
      },
      immediate: false
    },
    'form.a14': {
      handler(newVal, oldVal) {
        this.adjustA16Width();
      },
      immediate: false
    },
    'form.a15': {
      handler(newVal, oldVal) {
        this.adjustA16Width();
      },
      immediate: false
    },
  },

  created() {
    window.parent.getTemplateData((data, status) => {
      this.form = data;
      this.status = status;
    })
    window.postForm = () => {
      this.postForm();
    }
  },

  mounted() {
    window.parent.changeTemplateDow();
  },

  methods: {
    // a4，a5内容变化导致的行数变化
    adjustA4A5Rows() {
      // 计算字符串的字节数
      const newVal = this.form.a4 + this.form.a5;
      const charCount = newVal ? countChars(newVal) : 0;
      const { rows } = confirmRows(98, charCount);
      this.page.p1 = rows
    },
    // a13,a14,a15内容变化导致的行数变化
    adjustA13A14A15Rows() {
      // 计算字符串的字节数
      const newVal = this.form.a13 + this.form.a14 + this.form.a15;
      const charCount = newVal ? countChars(newVal) : 0;
      const { rows } = confirmRows(64, charCount);
      this.page.p12 = rows + 1
    },

    // a13,a14,a15内容变化导致的a16宽度调整函数
    adjustA16Width() {
      // 计算字符串的字节数
      const newVal = this.form.a13 + this.form.a14 + this.form.a15;
      const charCount = newVal ? countChars(newVal) : 0;
      const { rows, lastRowChars } = confirmRows(64, charCount);
      this.a16Config.firstLine.chars = 64 - lastRowChars - 1;
    },
    addClient() {
      this.form.client.push("")
    },
    delClient() {
      if (this.form.client.length > 1) {
        this.form.client.pop()
      } else {
        this.$message({
          message: '当事人至少保留一个',
          type: 'warning'
        })
      }
    },
    addProve() {
      this.form.evidence.push({
        name: '',
        prove: ''
      })
    },
    delProve() {
      if (this.form.evidence.length > 1) {
        this.form.evidence.pop()
      } else {
        this.$message({
          message: '证据至少保留一个',
          type: 'warning'
        })
      }
    },

    judgePage() {
      // 恢复原始的page
      this.controlPage = []
      // 计算动态的行数
      this.adjustA4A5Rows()
      this.adjustA13A14A15Rows()

      let row = 0;
      // 第一页可以放23行，第二页可以放27行
      let isFirstPage = true;
      // 处理当事人
      for (let i = 0; i < this.form.client.length; i++) {
        row += this.page.client
        if (isFirstPage) {
          if (row > 23) {
            this.controlPage.push(`client${i}`)
            row = this.page.client
            // 第一次分页了，将第一次标志位改为false
            isFirstPage = false
          }
        } else {
          if (row > 27) {
            this.controlPage.push(`client${i}`)
            row = this.page.client
          }
        }
      }
      // 处理p1-p3
      for (let i = 1; i <= 3; i++) {
        row += this.page[`p${i}`]
        if (isFirstPage) {
          if (row > 23) {
            this.controlPage.push(`p${i}`)
            row = this.page[`p${i}`]
            // 第一次分页了，将第一次标志位改为false
            isFirstPage = false
          }
        } else {
          if (row > 27) {
            this.controlPage.push(`p${i}`)
            row = this.page[`p${i}`]
          }
        }
      }
      // 处理证据
      for (let i = 0; i < this.form.evidence.length; i++) {
        row += this.page.evidence
        if (isFirstPage) {
          if (row > 23) {
            this.controlPage.push(`evidence${i}`)
            row = this.page.evidence
            // 第一次分页了，将第一次标志位改为false
            isFirstPage = false
          }
        } else {
          if (row > 27) {
            this.controlPage.push(`evidence${i}`)
            row = this.page.evidence
          }
        }
      }
      // 处理p4-p23
      for (let i = 4; i <= 23; i++) {
        row += this.page[`p${i}`]
        if (isFirstPage) {
          if (row > 23) {
            this.controlPage.push(`p${i}`)
            row = this.page[`p${i}`]
            // 第一次分页了，将第一次标志位改为false
            isFirstPage = false
          }
        } else {
          if (row > 27) {
            this.controlPage.push(`p${i}`)
            row = this.page[`p${i}`]
          }
        }
      }
      // 处理P24
      // 因为有盖章和其他信息占6行，需要单独判断最后一页的分页
      row += this.page.p24
      if (row > 21) {
        this.controlPage.push('p24')
        row = this.page.p24
      }

      this.sealPosition = 21 - row
    },
    // 切换单位删除线
    switchUnitDelLine() {
      this.form.isUnit = !this.form.isUnit
    },
    // 切换申辩删除线
    switchPleadDelLine() {
      this.form.isPlead = !this.form.isPlead
    },
    // 切换罚款删除线
    switchForfeitDelLine() {
      this.form.isHaveForfeit = !this.form.isHaveForfeit
    },

    // 导出为pdf
    exportPDF() {
      if (this.status !== '4') {
        this.isDisplay = false
      }
      this.savePDF()
        .then((blob) => {

          const blobUrl = URL.createObjectURL(blob);

          // 先预览
          const previewWindow = window.open(blobUrl, '_blank');

          // 自动下载
          const fileName = `行政处罚决定书.pdf`;
          const downloadLink = document.createElement('a');
          downloadLink.href = blobUrl;
          downloadLink.download = fileName;
          document.body.appendChild(downloadLink);
          downloadLink.click();
          document.body.removeChild(downloadLink);

          // 监听预览窗口关闭后释放内存
          if (previewWindow) {
            const timer = setInterval(() => {
              if (previewWindow.closed) {
                clearInterval(timer);
                URL.revokeObjectURL(blobUrl);
              }
            }, 1000);
          } else {
            setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); // 兜底释放
          }
        })
        .catch(error => {
          console.error('导出PDF出错:', error);
          alert('导出失败，请重试或联系管理员');
        });
    },
    savePDF() {
      this.judgePage()
      this.isPdfExport = true; // 激活PDF样式
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          import('html2pdf.js').then((module) => {
            const html2pdf = module.default;

            //获取所有需要替换的 el-input
            const elInputs = document.querySelectorAll('.el-input__inner, .el-textarea__inner');

            //存储原始元素和它们的父节点，方便后续恢复
            const originalElements = [];

            elInputs.forEach((input) => {
              const div = document.createElement('div');
              div.style.whiteSpace = 'pre-wrap'; // 保留换行
              div.style.fontFamily = '仿宋';
              div.style.fontSize = '19px';
              div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
              div.style.lineHeight = '30px';

              // 替换 el-input，并存储原始元素
              originalElements.push({
                parent: input.parentNode,
                original: input,
                replacement: div,
              });
              input.parentNode.replaceChild(div, input);
            });

            // 配置选项
            const opt = {
              margin: 0,
              image: {
                type: 'jpeg',
                quality: 0.98
              },
              html2canvas: {
                scale: 2,
                logging: false,
                useCORS: true
              },
              jsPDF: {
                unit: 'mm',
                format: 'a4',
                orientation: 'portrait'
              }
            };

            const element = document.getElementById('pdfDom');

            // 生成PDF Blob对象
            html2pdf()
              .set(opt)
              .from(element)
              .toPdf()
              .get('pdf')
              .then((pdf) => {
                const blob = pdf.output('blob');

                resolve(blob); // 返回Blob对象
              })
              .catch((error) => {
                reject(error);
              })
              .finally(() => {
                this.isPdfExport = false; // 恢复原始样式
                this.isDisplay = true;
                this.sealPosition = 0;
                // 恢复原始input
                originalElements.forEach(({ parent, original, replacement }) => {
                  parent.replaceChild(original, replacement);
                });
              });
          }).catch((error) => {
            reject(error);
            this.isPdfExport = false;
            this.isDisplay = true;
            this.sealPosition = 0;
            originalElements.forEach(({ parent, original, replacement }) => {
              parent.replaceChild(original, replacement);
            });
          });
        });
      });
    },
    //父页面提交按钮将调用此方法，此方法将文书数据回传到父页面的请求方法中
    postForm() {
      this.savePDF()
        .then((blob) => {
          // 创建FormData并添加文件
          const formData = new FormData();
          formData.append('file', blob, '行政处罚决定书.pdf');

          window.parent.postTemplateDate(this.form, formData);
        })
        .catch(error => {
          console.error('整个保存PDF出错:', error);
        });
    },
    //选择日期时间
    receiveFromChild(data, type) {
      const TypeMap = {
        'YYYYMMDD1': 'date1',
        'YYYYMMDD2': 'date2',
        'YYYYMMDD3': 'date3',
        'YYYYMMDD4': 'date4',
        'YYYYMMDD5': 'date5',
        'YYYYMMDD6': 'date6',
        'YYYYMMDD7': 'date7',
      };
      if (TypeMap[type]) {
        this.form[TypeMap[type]] = data;
      }
    },
  }
}
</script>

<style scoped>
/* 增加和删除按钮样式 */
.pdf-export .el-button-addAndDel {
  display: none;
}

:deep(.el-button-addAndDel .el-button) {
  display: inline-flex !important;
  z-index: 1 !important;
  width: auto;
  min-width: 100px;
  height: auto;
  padding: 8px 15px;
  color: #000 !important;
}
.official-seal {
  /* 公章隐藏，在打印时显示*/
  display: none;
  width: 4.2cm;
  height: 4.2cm;
  z-index: 20;

  /* 定位 */
  position: absolute;
  bottom: -20px;
  right: -10px;
}


:deep(.el-button-print .el-button) {
  display: inline-flex !important;
  visibility: visible !important;
  opacity: 1 !important;
  width: auto;
  min-width: 100px;
  height: auto;
  padding: 8px 15px;
  background: #fff !important;
  color: #000 !important;
  border: none;
}

:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 19px;
  overflow-y: hidden;
  line-height: 30px;
  white-space: pre-wrap;
}

:deep(.el-textarea-hidden .el-textarea__inner) {
  box-shadow: 0 0 0 0;
  color: black;
  padding: 0;
  font-family: "仿宋", serif;
  font-size: 19px;
  overflow-y: hidden !important;
  resize: none !important;
  height: auto !important;
}

.input-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.inputStyleNoLine {
  border: none;
  outline: none;
  padding: 0px;
}

.typeSpan {
  cursor: pointer;
  font-size: 5mm;
}
</style>
